import { AssignRoleItem, ResetUserPassItem, UserItem } from '@/types/user';
import { PageQueryParamType, pageRequest, sendPostRequest, sendGetJsonRequest } from '@/utils/requestEx';
import { loadingCache } from './system';

export async function queryCurrent(params: any): Promise<any> {
  let { userId } = params;
  if (!userId) {
    userId = '20';
  }
  const endPointURI = `/dev/user/current/${userId}`;
  return sendGetJsonRequest(endPointURI, params);
}

/**
 * 分页查询参条件
 * @param paramName 可输，参数名称
 * @param paramKey 可输，参数键名
 */
export interface UserQueryType extends PageQueryParamType {
  paramName?: string;
  paramKey?: string;
}

export async function fetchUsersByRole(params: any) {
  // const { roleCode } = params;
  // // 判断会话缓存中是否有缓存
  // const userListStr = sessionStorage.getItem(roleCode);
  // if (userListStr) {
  //   // 会话缓存中存在，则取缓存，不再去服务端通讯
  //   const result = JSON.parse(userListStr);
  //   return Promise.resolve(result);
  // }
  // const endPointURI = `/dev/user/role/${roleCode}`;
  // const res = sendGetJsonRequest(endPointURI, params);
  // res.then(data => {
  //   const resStr = JSON.stringify(data);
  //   sessionStorage.setItem(roleCode, resStr);
  // });
  // return res;
  const { roleCode } = params;
  const endPointURI = '/dev/user/role';
  return loadingCache(roleCode, endPointURI);
}

export async function fetchAllUser(params: UserQueryType) {
  const endPointURI = '/dev/user/list';
  return pageRequest(endPointURI, params);
}

export async function resetUserPass(params: ResetUserPassItem) {
  const endPointURI = '/dev/user/reset/password';
  return sendPostRequest(endPointURI, params);
}

export async function addUser(params: UserItem) {
  const endPointURI = '/dev/user/insert';
  return sendPostRequest(endPointURI, params);
}

export async function updateUser(params: UserItem) {
  const endPointURI = '/dev/user/update';
  return sendPostRequest(endPointURI, params);
}

export async function deleteUsers(params: any) {
  const { userId } = params;
  const endPointURI = `/dev/user/delete/${userId}`;
  return sendGetJsonRequest(endPointURI, params);
}

export async function fetchRolesByUser(params: any) {
  const { userId } = params;
  const endPointURI = `/dev/user/assigned/role/${userId}`;
  return sendGetJsonRequest(endPointURI, params);
}

export async function assignRolesToUser(params: AssignRoleItem) {
  const endPointURI = `/dev/user/assign/role`;
  return sendPostRequest(endPointURI, params);
}